package org.springblade.modules.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.plan.score.PlanScoreSearchDTO;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.enums.MaintainPlanContentEnum;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.vo.PlanCheckHistoryScoreVO;
import org.springblade.modules.admin.vo.PlanTemplateVO;
import org.springblade.modules.admin.vo.plan.store.*;
import org.springblade.modules.admin.vo.score.WxScoreFailureVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zcc
 * @version 1.0
 * @date 2024/1/4 10:55
 */
@RestController
@AllArgsConstructor
@RequestMapping("admin/maintainplan/score")
@Api(value = "评分管理", tags = "评分管理")
public class MaintainPlanScoreController {


	private final IMaintainPlanContentService maintainPlanContentService;
	private final IMaintainPlanContentExtService maintainPlanContentExtService;
	private final MaintainMsgService msgService;
	private final MaintainPlanScoreService maintainPlanScoreService;
	private final BladeRedis bladeRedis;
	private final IPlanHistoryScoreService planHistoryScoreService;
	private final IMaintainMalfunctionHistoryService maintainMalfunctionHistoryService;
	private final IPlanScoreDimensionService planScoreDimensionService;
	private final MaintainCheckRecordService maintainCheckRecordService;
	private final RedisTemplate redisTemplate;
	private final static String SCORE_MESSAGE_KEY = "score:message:user:";
	private final IWxFaultCauseService wxFaultCauseService;
	private final IWxFaultTypeService wxFaultTypeService;
	private final IPlanCheckHistoryScoreService planCheckHistoryScoreService;

	@PostMapping("getPlanScoreList")
	@ApiOperation(value = "保养已抽检列表")
	public R<IPage<PlanScoreListVo>> getPlanScoreList(@RequestBody PlanScoreSearchDTO planScoreSearchDTO) {
		if (planScoreSearchDTO.getScoreType() != null && Convert.toInt(planScoreSearchDTO.getScoreStatus(), -1) == 0) {
			return R.data(new Page<>());
		} else {
			if (planScoreSearchDTO.getScoreType() != null) {
				planScoreSearchDTO.setScoreStatus(1);
			}
		}
		IPage<PlanScoreListVo> page = maintainPlanContentService.getPlanScoreList(planScoreSearchDTO);
		return R.data(page);
	}


	@PostMapping("getDisPlanScoreList")
	@ApiOperation(value = "保养待评分列表")
	public R<IPage<PlanScoreListVo>> getDisPlanScoreList(@RequestBody PlanScoreSearchDTO planScoreSearchDTO) {
		if (planScoreSearchDTO.getRatio() == null) {
			planScoreSearchDTO.setRatio(Convert.toBigDecimal(1));
		}
		IPage<PlanScoreListVo> page = maintainPlanContentService.getDisPlanScoreList(planScoreSearchDTO);
		return R.data(page);
	}


	@GetMapping("getPlanScoreMonthList")
	@ApiOperation(value = "月份统计接口")
	public R<List<PlanScoreMonthVo>> getPlanScoreMonthList(Date beginTime, Date endTime, Integer typeStatus) {

		return R.data(maintainPlanContentService.getPlanScoreMonthList(beginTime, endTime, typeStatus));
	}


	@PostMapping("removeBatchScore")
	@ApiOperation(value = "批量刪除抽检工单")
	public R<Boolean> removeBatchScore(@RequestBody List<Long> planIds) {
		List<MaintainPlanContentExt> planContentExts = maintainPlanContentExtService.list(Wrappers.<MaintainPlanContentExt>lambdaQuery().in(MaintainPlanContentExt::getPlanId, planIds));
		for (MaintainPlanContentExt maintainPlanContentExt : planContentExts) {
			maintainPlanContentExt.setScoreSpotCheckType(0);
		}
		List<List<MaintainPlanContentExt>> partition = Lists.partition(planContentExts, 20);
		for (List<MaintainPlanContentExt> list : partition) {
			maintainPlanContentExtService.updateBatchById(list);
		}
		return R.data(true);
	}


	@PostMapping("addBatchScore")
	@ApiOperation(value = "批量添加抽检工单")
	public R<Boolean> addBatchScore(@RequestBody List<String> planIds) {
		List<MaintainPlanContentExt> planContentExts = maintainPlanContentExtService.list(Wrappers.<MaintainPlanContentExt>lambdaQuery().in(MaintainPlanContentExt::getPlanId, planIds));
		Integer scoreSpotCheckType = 1;
		for (MaintainPlanContentExt maintainPlanContentExt : planContentExts) {
			maintainPlanContentExt.setScoreSpotCheckDate(new Date());
			maintainPlanContentExt.setScoreSpotCheckType(scoreSpotCheckType);
		}
		List<List<MaintainPlanContentExt>> partition = Lists.partition(planContentExts, 20);
		for (List<MaintainPlanContentExt> list : partition) {
			maintainPlanContentExtService.updateBatchById(list);
		}
		return R.data(true);
	}

	@PostMapping("addBatchScore/all")
	@ApiOperation(value = "批量添加抽检工单")
	public R<Boolean> addBatchScoreAll(@RequestBody PlanScoreSearchDTO planScoreSearchDTO) {
		if (planScoreSearchDTO.getRatio() == null) {
			planScoreSearchDTO.setRatio(Convert.toBigDecimal(1));
		}
		List<Long> planIds = maintainPlanContentService.getDisPlanScoreAll(planScoreSearchDTO);
		if (planIds.size() == 0) {
			return R.data(true);
		}
		List<MaintainPlanContentExt> planContentExts = maintainPlanContentExtService.list(Wrappers.<MaintainPlanContentExt>lambdaQuery().in(MaintainPlanContentExt::getPlanId, planIds));
		Integer scoreSpotCheckType = 1;
		List<MaintainPlanContentExt> updateList = new ArrayList<>(1000);
		for (MaintainPlanContentExt maintainPlanContentExt : planContentExts) {
			MaintainPlanContentExt maintainPlanContentExt1 = new MaintainPlanContentExt();
			maintainPlanContentExt1.setId(maintainPlanContentExt.getId());
			maintainPlanContentExt1.setScoreSpotCheckDate(new Date());
			maintainPlanContentExt1.setScoreSpotCheckType(scoreSpotCheckType);
			updateList.add(maintainPlanContentExt1);
		}
		List<List<MaintainPlanContentExt>> partition = Lists.partition(updateList, 200);
		for (List<MaintainPlanContentExt> list : partition) {
			maintainPlanContentExtService.updateBatchById(list);
		}
		return R.data(true);
	}


	@GetMapping("addScoreMessage")
	@ApiOperation(value = "发送待评分消息")
	public R<Boolean> adminBatchScore() {
		RedisTemplate<String, Object> redisTemplate = bladeRedis.getRedisTemplate();
		Long userId = AuthUtil.getUserId();
		String toStr = Convert.toStr(redisTemplate.opsForValue().get(SCORE_MESSAGE_KEY + userId));
		if (StrUtil.isNotEmpty(toStr)) {
			return R.data(true);
		}
		List<Long> userIds = new ArrayList<>(1);
		userIds.add(userId);
		//表示未评分
		Integer scoreStatus = 0;
		List<MaintainPlanContentExt> list = maintainPlanContentExtService.list(Wrappers.<MaintainPlanContentExt>lambdaQuery().isNotNull(MaintainPlanContentExt::getPlanEndTime).eq(MaintainPlanContentExt::getScoreStatus, scoreStatus).between(MaintainPlanContentExt::getScoreSpotCheckDate, DateUtil.beginOfMonth(new Date()), new Date()));
		if (list.size() > 0) {
			MaintainMsg msg = new MaintainMsg();
			msg.setTitle("系统消息");
			msg.setContent("[待评分] 工单提醒");
			msg.setType(MaintainPlanContentEnum.SCORE_BY.getId());
			msgService.sendMsg(msg, userIds);
		}
		long between = DateUtil.between(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), DateUnit.MINUTE);
		redisTemplate.opsForValue().set(SCORE_MESSAGE_KEY + userId, "true", between, TimeUnit.MINUTES);
		return R.data(true);
	}


	@PostMapping("/down/excel")
	@ApiOperationSupport(order = 34)
	@ApiOperation(value = "下载抽检评分")
	public void downList(HttpServletResponse response, @RequestBody PlanScoreSearchDTO planScoreSearchDTO) throws IOException {
		List<PlanScoreListVo> list;
		if (planScoreSearchDTO.getScoreType() != null && Convert.toInt(planScoreSearchDTO.getScoreStatus(), -1) == 0) {
			list = new ArrayList<>(16);
		} else {
			if (planScoreSearchDTO.getScoreType() != null) {
				planScoreSearchDTO.setScoreStatus(1);
			}
			list = maintainPlanContentService.getPlanScoreListDownExcel(planScoreSearchDTO);
		}
		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			List<List<String>> rows = new ArrayList<>();
			List<String> title = CollUtil.newArrayList("项目名称", "电梯位置", "计划执行人", "当前计划时间", "实际执行人", "开始时间", "完成时间", "有效判定", "工单评分", "整体评价", "问题数量", "评分人", "评分时间", "添加时间", "任务状态", "评分状态");
			rows.add(title);
			for (PlanScoreListVo planScoreListVo : list) {
				Integer scoreStatus = Convert.toInt(planScoreListVo.getScoreStatus(), 0);
				if (scoreStatus == 0) {
					planScoreListVo.setScore(Convert.toBigDecimal(0));
					planScoreListVo.setScoreType(null);
					planScoreListVo.setScoreUserName(null);
					planScoreListVo.setScoreDate(null);
				}
				List<String> row = new ArrayList<>();
				row.add(Convert.toStr(planScoreListVo.getBuildingName()));
				row.add(Convert.toStr(planScoreListVo.getElevatorAddress()));
				row.add(Convert.toStr(planScoreListVo.getPlanUserNames()));
				row.add(DateUtil.format(planScoreListVo.getPlanDate(), "yyyy-MM-dd"));
				row.add(Convert.toStr(planScoreListVo.getPlanUserNames()));
				if (planScoreListVo.getPlanBeginTime() != null) {
					row.add(DateUtil.format(planScoreListVo.getPlanBeginTime(), "yyyy-MM-dd"));
				} else {
					row.add("/");
				}
				if (planScoreListVo.getPlanEndTime() != null) {
					row.add(DateUtil.format(planScoreListVo.getPlanEndTime(), "yyyy-MM-dd"));
				} else {
					row.add("/");
				}
				//评分类型1:有效订单，2：无效工单3：无法判断
				if (planScoreListVo.getScoreType() != null) {
					if (planScoreListVo.getScoreType() == 1) {
						row.add("有效工单");
					} else if (planScoreListVo.getScoreType() == 2) {
						row.add("无效工单");
					} else if (planScoreListVo.getScoreType() == 3) {
						row.add("无法判断");
					}
				} else {
					row.add("/");
				}
				if (Convert.toStr(planScoreListVo.getScore(), "0.0").equals("0.0") || Convert.toStr(planScoreListVo.getScore(), "0").equals("0")) {
					row.add("/");
				} else {
					row.add(Convert.toStr(planScoreListVo.getScore(), "/"));
				}
				row.add(Convert.toStr(planScoreListVo.getScoreFutilityDesc(), "/"));
				row.add(Convert.toStr(planScoreListVo.getQuestionCounts(), "0"));
				row.add(Convert.toStr(planScoreListVo.getScoreUserName(), "/"));
				if (planScoreListVo.getScoreDate() != null) {
					row.add(DateUtil.format(planScoreListVo.getScoreDate(), "yyyy-MM-dd"));
				} else {
					row.add("/");
				}
				if (planScoreListVo.getScoreSpotCheckDate() != null) {
					row.add(DateUtil.format(planScoreListVo.getScoreSpotCheckDate(), "yyyy-MM-dd"));
				} else {
					row.add("/");
				}
				row.add(Convert.toStr(planScoreListVo.getPlanStatusName()));
				row.add(scoreStatus == 0 ? "未评分" : "已评分");
				rows.add(row);
			}
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			setResponseHeader(response, fileName);
			excelWriter = ExcelUtil.getBigWriter(rows.size());
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (
			Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}
	}


	@GetMapping("getByPlanDetail")
	@ApiOperation(value = "保养评分-基础信息")
	public R<ScoreByDetailVo> getByPlanDetail(Long planId) {
		ScoreByDetailVo scoreByDetailVo = maintainPlanScoreService.getByPlanDetail(planId);
		return R.data(scoreByDetailVo);
	}


	/**
	 * 获取任务工作项
	 *
	 * @param planId
	 * @param templateId
	 * @return
	 */
	@GetMapping("/work/item")
	@ApiOperation(value = "保养工作项")
	public R<List<PlanTemplateVO>> workItem(Long planId, Long templateId, Long checkHistoryId) {
		return R.data(maintainPlanScoreService.getPlanWorkItem(planId, templateId, checkHistoryId));
	}


	/**
	 * 获取任务工作项
	 *
	 * @param planIds 工单ids
	 * @return 数据集
	 */
	@GetMapping("/getScoreByCountDetail")
	@ApiOperation(value = "保养-工作项评分次数")
	public R<List<ScoreByCountVo>> getScoreByCountDetail(String planIds) {
		return R.data(maintainPlanScoreService.getScoreByCountDetail(planIds));
	}


	/**
	 * 获取保养工作项里面的评分信息
	 *
	 * @param checkHistoryId   工作项
	 * @param scoreDimensionId 工作项绑定评分模板
	 * @param isUpdate         true表示更新，false 正常新增
	 * @return 数据集
	 */
	@GetMapping("/getScoreTemplate")
	@ApiOperation(value = "获取保养评分信息")
	public R<PlanCheckHistoryScore> getScoreTemplate(Long checkHistoryId, Long scoreDimensionId, Boolean isUpdate) {
		if (isUpdate == null) {
			isUpdate = false;
		}
		return R.data(maintainPlanScoreService.getScoreTemplate(checkHistoryId, scoreDimensionId, isUpdate));
	}


	/**
	 * 工作项添加评分，或者更新评分
	 *
	 * @param planCheckHistoryScoreVO 参数值
	 * @return 数据集
	 */
	@PostMapping("/saveAndUpdateScore")
	@ApiOperation(value = "保存更新工作项评分")
	public R<Boolean> saveAndUpdateScore(@RequestBody PlanCheckHistoryScoreVO planCheckHistoryScoreVO) {
		if (planCheckHistoryScoreVO.getCheckHistoryId() == null) {
			throw new ServiceException("工单项id不能为空");
		}
		Boolean aBoolean = getAddScoreWorkId(Convert.toStr(planCheckHistoryScoreVO.getCheckHistoryId()));
		if (aBoolean) {
			maintainPlanScoreService.saveAndUpdateScore(planCheckHistoryScoreVO);
		} else {
			throw new ServiceException("操作过快...");
		}
		return R.data(true);
	}


	/**
	 * 工单评分-更新
	 *
	 * @param planCheckHistoryScoreVO 参数值
	 * @return 数据集
	 */
	@PostMapping("/updatePlanScore")
	@ApiOperation(value = "更新工单评分")
	public R<Boolean> updatePlanScore(@RequestBody PlanCheckHistoryScoreVO planCheckHistoryScoreVO) {
		maintainPlanScoreService.updatePlanScore(planCheckHistoryScoreVO);
		return R.data(true);
	}


	@GetMapping("/deleteCheckScore")
	@ApiOperation(value = "删除工作项工单")
	public R<Boolean> deleteCheckScore(Long checkHistoryId) {
		maintainPlanScoreService.delete(checkHistoryId);
		return R.data(true);
	}

	@GetMapping("/getSignScoreType")
	@ApiOperation(value = "当前租户打卡评分项")
	public R<Long> getSignScoreType() {
		PlanScoreDimension scoreDimension = planScoreDimensionService.getOne(Wrappers.<PlanScoreDimension>lambdaQuery().eq(PlanScoreDimension::getPrefixCode, "DK"));
		if (scoreDimension == null) {
			throw new ServiceException("当前租户没有设置打卡评分项");
		} else {
			return R.data(scoreDimension.getId());
		}
	}

	@GetMapping("getPlanScoreHistorys")
	@ApiOperation("工单评分历史")
	public R<List<PlanHistoryScore>> getPlanScoreHistorys(Long planId) {
		List<PlanHistoryScore> list = planHistoryScoreService.list(Wrappers.<PlanHistoryScore>lambdaQuery().eq(PlanHistoryScore::getPlanId, planId).orderByDesc(PlanHistoryScore::getCreateTime));
		return R.data(list);
	}


	@GetMapping("planScoreCheck")
	@ApiOperation("校验工作项是否评分")
	public R<ScoreCheckVo> planScoreCheck(Long planId) {
		return R.data(maintainPlanScoreService.planScoreCheck(planId));
	}


	@GetMapping("planScoreCheck/v2")
	@ApiOperation("工作项跳转上一个")
	public R<ScoreCheckVo> planScoreCheckV2(Long planId, Long templateId) {
		return R.data(maintainPlanScoreService.planScoreCheckV2(planId, templateId));
	}

//2024-04-16新增维修评分,需求复杂多变,所以和保养评分不共用


	/**
	 * 获取维修工单评分进度
	 *
	 * @param planIds 工单ids
	 * @return 数据集
	 */
	@GetMapping("/getScoreByCountDetail/wx")
	@ApiOperation(value = "维修-工作项评分次数")
	public R<List<ScoreByCountVo>> getScoreByCountDetailWx(String planIds) {
		return R.data(maintainPlanScoreService.getScoreByCountDetailWx(planIds));
	}


	@PostMapping("getPlanScoreList/wx")
	@ApiOperation(value = "维修-评分列表-1")
	public R<IPage<PlanScoreListVo>> getPlanScoreListWx(@RequestBody PlanScoreSearchDTO planScoreSearchDTO) {
		if (planScoreSearchDTO.getScoreType() != null && Convert.toInt(planScoreSearchDTO.getScoreStatus(), -1) == 0) {
			return R.data(new Page<>());
		} else {
			if (planScoreSearchDTO.getScoreType() != null) {
				planScoreSearchDTO.setScoreStatus(1);
			}
		}
		IPage<PlanScoreListVo> page = maintainPlanContentService.getPlanScoreListWx(planScoreSearchDTO);
		return R.data(page);
	}


	/**
	 * 获取维修-配件的评分信息
	 *
	 * @param workId 维修work表的id
	 * @return 数据集
	 */
	@GetMapping("/getScore/wx/question")
	@ApiOperation(value = "维修-获取评分信息-2")
	public R<PlanCheckHistoryScore> getScoreWx(Long workId) {
		return R.data(maintainPlanScoreService.getScoreWxInfo(workId));
	}


	/**
	 * 维修-针对维修记录评分
	 */
	@PostMapping("/save/wx/question")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "维修-保存评分信息-3", notes = "one")
	public R<Boolean> saveWxQuestion(@RequestBody WxStoreAddQuestionVo wxStoreAddQuestionVo) {
		maintainMalfunctionHistoryService.saveWxQuestion(wxStoreAddQuestionVo);
		return R.data(true);
	}


	/**
	 * 保养-针对保养记录评分
	 */
	@PostMapping("/save/by/question")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "保养-保存评分信息-3", notes = "one")
	public R<Boolean> saveByQuestion(@RequestBody WxStoreAddQuestionVo wxStoreAddQuestionVo) {
		maintainMalfunctionHistoryService.saveByQuestion(wxStoreAddQuestionVo);
		return R.data(true);
	}


	/**
	 * 保养-针对保养记录评分
	 */
	@GetMapping("/remove/question")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "删除评分问题点", notes = "one")
	public R<Boolean> removeByQuestion(Long id) {
		MaintainMalfunctionHistory malfunctionHistory = maintainMalfunctionHistoryService.getById(id);
		if (malfunctionHistory != null && malfunctionHistory.getChildPlanId() != null) {
			throw new ServiceException("已创建工单无法删除");
		}
		if (malfunctionHistory == null) {
			throw new ServiceException("找不到对应的工作项");
		}
		maintainMalfunctionHistoryService.removeById(id);
		return R.data(true);
	}


	/**
	 * 维修-工单评分-更新
	 *
	 * @param planCheckHistoryScoreVO 参数值
	 * @return 数据集
	 */
	@PostMapping("/updatePlanScore/wx")
	@ApiOperation(value = "維修-更新工单评分")
	public R<Boolean> updatePlanScoreWx(@RequestBody PlanCheckHistoryScoreVO planCheckHistoryScoreVO) {
		maintainPlanScoreService.updatePlanScoreWx(planCheckHistoryScoreVO);
		return R.data(true);
	}


	/**
	 * 新增 故障工单明细
	 */
	@GetMapping("/wx/question/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "维修问题列表", notes = "one")
	public R<List<MaintainMalfunctionHistory>> wxQuestionList(Long planId, Long workId) {
		List<MaintainMalfunctionHistory> list;
		if (workId == null) {
			list = maintainMalfunctionHistoryService.list(Wrappers.<MaintainMalfunctionHistory>lambdaQuery().eq(MaintainMalfunctionHistory::getPlanId, planId).isNotNull(MaintainMalfunctionHistory::getScoreWorkId).orderByAsc(MaintainMalfunctionHistory::getCreateTime));
			//暂时采用循序的方式,因为每个工单的问题数量不多
			for (MaintainMalfunctionHistory maintainMalfunctionHistory : list) {
				List<MaintainCheckRecord> records = maintainCheckRecordService.list(Wrappers.<MaintainCheckRecord>lambdaQuery().eq(MaintainCheckRecord::getCheckHistoryId, maintainMalfunctionHistory.getId()));
				maintainMalfunctionHistory.setRecordList(records);
			}
		} else {
			list = maintainMalfunctionHistoryService.list(Wrappers.<MaintainMalfunctionHistory>lambdaQuery().eq(MaintainMalfunctionHistory::getPlanId, planId).eq(MaintainMalfunctionHistory::getScoreWorkId, workId).orderByAsc(MaintainMalfunctionHistory::getCreateTime));
		}
		return R.data(list);
	}


	/**
	 * 新增 故障工单明细
	 */
	@GetMapping("/wx/question/list/v2")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "维修问题列表", notes = "one")
	public R<List<PlanCheckHistoryScore>> wxQuestionListV2(Long planId) {
		List<PlanCheckHistoryScore> list = planCheckHistoryScoreService.getPlanCheckHistoryScoreList(planId);
		Map<Long, List<WxFaultCause>> wxFaultCauseMap = wxFaultCauseService.list().stream().collect(Collectors.groupingBy(WxFaultCause::getId));
		Map<Long, List<WxFaultType>> wxFaultTypeMap = wxFaultTypeService.list().stream().collect(Collectors.groupingBy(WxFaultType::getId));
		for (PlanCheckHistoryScore planCheckHistoryScore : list) {
			if (StrUtil.isNotEmpty(planCheckHistoryScore.getWxFaultCauseIds())) {
				List<String> ids = Func.toStrList(planCheckHistoryScore.getWxFaultCauseIds());
				List<String> names = new ArrayList<>(16);
				for (String id : ids) {
					List<WxFaultCause> wxFaultCauses = wxFaultCauseMap.get(Convert.toLong(id));
					if (wxFaultCauses != null && wxFaultCauses.size() > 0) {
						names.add(wxFaultCauses.get(0).getFaultName());
					}
				}
				if (names.contains("其他")) {
					names.remove("其他");
					names.add("其他-" + planCheckHistoryScore.getWxFaultCauseDesc());
				}
				planCheckHistoryScore.setWxFaultCauseNames(names);
			}

			if (StrUtil.isNotEmpty(planCheckHistoryScore.getWxFaultTypeIds())) {
				List<String> ids = Func.toStrList(planCheckHistoryScore.getWxFaultTypeIds());
				List<String> names = new ArrayList<>(16);
				for (String id : ids) {
					List<WxFaultType> wxFaultCauses = wxFaultTypeMap.get(Convert.toLong(id));
					if (wxFaultCauses != null && wxFaultCauses.size() > 0) {
						names.add(wxFaultCauses.get(0).getName());
					}
				}
				if (names.contains("其他")) {
					names.remove("其他");
					names.add("其他-" + planCheckHistoryScore.getWxFaultTypeDesc());
				}
				planCheckHistoryScore.setWxFaultCauseNames(names);
			}
		}

		return R.data(list);
	}


//=================================================2025-03-03 维修评分迭代=============================================================

	@PostMapping("getDisPlanScoreList/wx")
	@ApiOperation(value = "维修-待抽检列表")
	public R<IPage<PlanScoreListVo>> getDisPlanScoreListWx(@RequestBody PlanScoreSearchDTO planScoreSearchDTO) {
		if (planScoreSearchDTO.getRatio() == null) {
			planScoreSearchDTO.setRatio(Convert.toBigDecimal(1));
		}
		IPage<PlanScoreListVo> page = maintainPlanContentService.getDisPlanScoreListWx(planScoreSearchDTO);
		return R.data(page);
	}


	@PostMapping("getWxByPlanHistoryList")
	@ApiOperation(value = "维修保养历史工单列表")
	public R<List<WxByPlanHistoryVo>> getWxByPlanHistoryList(@RequestBody PlanScoreSearchDTO planScoreSearchDTO) {
		if (planScoreSearchDTO.getBeginPlanTime() == null) {
			planScoreSearchDTO.setBeginPlanTime(DateUtil.offsetDay(new Date(), -90));
			planScoreSearchDTO.setEndPlanTime(new Date());
		}
		return R.data(maintainPlanScoreService.getWxByPlanHistoryList(planScoreSearchDTO));
	}


	@GetMapping("getWxScoreFailureList")
	@ApiOperation("维修-部件判断结果列表")
	public R<List<WxScoreFailureVo>> getWxScoreFailureList(Long planId) {

		return R.data(maintainPlanScoreService.getWxScoreFailureList(planId));
	}


	/**
	 * 功能描述: 发送响应流方法
	 */
	private void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * 校验保养评分项工作项
	 *
	 * @param workId 工作项id
	 * @return 数据集
	 */
	private synchronized Boolean getAddScoreWorkId(String workId) {
		String toStr = Convert.toStr(redisTemplate.opsForValue().get(workId));
		if (StrUtil.isEmpty(toStr)) {
			redisTemplate.opsForValue().set(workId, workId, 1, TimeUnit.SECONDS);
			return true;
		} else {
			return false;
		}
	}
}
